package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.mapper.ProductMapper;
import com.ruoyi.system.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Date;

@Service
public class ProductServiceImpl implements IProductService {
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    @Override
    public Product selectProductById(Long productId) {
        return productMapper.selectProductById(productId);
    }

    @Override
    @Transactional
    public int insertProduct(Product product) {
        product.setCreatedAt(new Date());
        return productMapper.insertProduct(product);
    }

    @Override
    @Transactional
    public int updateProduct(Product product) {
        return productMapper.updateProduct(product);
    }

    @Override
    @Transactional
    public int deleteProductByIds(Long[] productIds) {
        return productMapper.deleteProductByIds(productIds);
    }

    @Override
    @Transactional
    public int deleteProductById(Long productId) {
        return productMapper.deleteProductById(productId);
    }

    @Override
    @Transactional
    public int updateStock(Long productId, Integer quantity) {
        Product product = productMapper.selectProductById(productId);
        if (product == null) {
            throw new ServiceException("产品不存在");
        }
        
        // 如果是减库存，检查库存是否足够
        if (quantity < 0 && product.getStock() < Math.abs(quantity)) {
            throw new ServiceException("库存不足");
        }
        
        return productMapper.updateStock(productId, quantity);
    }
} 